Friend Keyword in C++ (ENG)

Friend Declaration

In C++, we use the friend keyword in the class body to declare a function or a class as a friend to the current class. This means that the friend function or class will have access to the private and protected members of the current class. The declaration syntax is as follows:

class MyClass {
    int a, b, c; // private members

    // Friend function declaration
    friend void printMember();

    // Friend class declaration
    friend class AnotherClass;
};
#include <iostream>

class MyClass {
private:
    int a, b, c;

public:
    MyClass(int x, int y, int z) : a(x), b(y), c(z) {}

    // Declare AnotherClass as a friend
    friend class AnotherClass;
};

class AnotherClass {
public:
    void showValues(const MyClass& obj) {
        std::cout << "a: " << obj.a << ", b: " << obj.b << ", c: " << obj.c << std::endl;
    }
};

int main() {
    MyClass obj(1, 2, 3);
    AnotherClass anotherObj;
    anotherObj.showValues(obj); // Friend class can access private members
    return 0;
}

Double-Edge Sword

Interestingly, the friendship friend brings is not transitive, which means a friend of your friend is not your friend. Additionally, friendship is not inherited.

Using the friend keyword makes private data transparent, which can be convenient, but it breaks the encapsulation of a class. In most cases, your code should not include any friend declarations, as this might indicate poor design.

One of the most common use cases for the friend keyword in C++ is in non-member operator overloads. By declaring a non-member operator function as a friend, you grant it access to the private and protected members of your class. This is particularly useful for operator overloading, such as the << operator for output streams.

#include <iostream>

class MyClass {
private:
    int a, b, c; // private members

public:
    MyClass(int x, int y, int z) : a(x), b(y), c(z) {}

    // Friend function declaration for operator<<
    friend std::ostream& operator<<(std::ostream& os, const MyClass& obj);
};

// Definition for operator<<
std::ostream& operator<<(std::ostream& os, const MyClass& obj) {
    os << "a: " << obj.a << ", b: " << obj.b << ", c: " << obj.c;
    return os;
}

int main() {
    MyClass obj(1, 2, 3);
    std::cout << obj << std::endl; // Uses the friend function to access private members
    return 0;
}